package main.request;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import utils.Debug;
import main.process.FtpRequest;

public class RequestCdup implements ProcessRequestInterface {
	private static class SingletonHolder
	{		
		/** Instance unique non préinitialisée */
		private final static RequestCdup instance = new RequestCdup();
	}
	
	public static RequestCdup getInstance()
	{
		return SingletonHolder.instance;
	}
	
	@Override
	public void processRequest(String[] request, FtpRequest ftp) throws IOException {
		Debug.debug(this.getClass().getName(), request, ftp.getDebug());
		
		if(!request[0].equals("CDUP"))
		{
			next(request, ftp);
		}
		else
		{
			String dest = "";
			Path path = Paths.get(ftp.getPathName());
			for (int i = 0; i < path.getNameCount()-1; i++) 
			{
				dest = dest  + "/"  + path.getName(i);
			}
			System.out.println(dest);
			if(dest.startsWith(ftp.getRoot())){
				ftp.setPathName(dest);
				ftp.write("250 CDUP ok\n");	
			}
			else{
				ftp.setPathName(ftp.getRoot());
				ftp.write("550 access denied\n");
			}
		}
	}

	@Override
	public void next(String[] request, FtpRequest ftp) throws IOException {
		RequestCwd.getInstance().processRequest(request, ftp);

	}

}
